InjectJsCallback

public interface InjectJsCallback implements BrowserSyncCallback<P, R>

This callback is invoked when the document element has been created and a custom JavaScript can be injected into the document.

You can inject a custom JavaScript code using the executeJavaScript method. This callback is intended to give you an opportunity to inject a Java object into JavaScript code or inject a custom JavaScript code for further execution before any scripts are executed in the frame. For example:


browser.set(InjectJsCallback.class, params -> {
    JsObject window = params.frame().executeJavaScript("window");
    if (window != null) {
        window.putProperty("java", new JavaObject());
    }
    return InjectJsCallback.Response.proceed();
});
The JavaObject class may look like this:
public class JavaObject {
   
@JsAccessible
public String sayHelloTo(String firstName) { return "Hello " + firstName + "!"; } }

When the property is set, you can call methods of the injected Java object from JavaScript:

window.java.sayHelloTo('John');

Return the proceed response from the callback to continue loading the frame.

If the callback throws an exception, the InjectJsCallback.proceed() method will be invoked.

This callback may be invoked several times for the same frame.

Important: you should avoid executing a JavaScript code that modifies the DOM tree of the web page being loaded. You must not use JxBrowser DOM API to remove the frame for which this callback is invoked, otherwise the render process will crash.

Important: the engine will be blocked until you return control from the callback.

Types

Link copied to clipboard
public interface Params
The parameters of the InjectJsCallback.
Link copied to clipboard
public interface Response
A response of the InjectJsCallback.

Functions

Link copied to clipboard
@CheckForNull()
public abstract R on(P params)
Invoked when the callback needs a response of type R that may be determined based on the provided callback parameters.